package realtime;

import java.awt.Cursor;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;


import messagepasser.*;

public class SendDocumentState extends TimerTask {
	private MessagePasser myPasser;
	private Timer myTimer;
//	private Lab0Test app;
	private String consistentState;
	private boolean noChange = true;

	
	public SendDocumentState(MessagePasser passer, Timer t) {
		myPasser = passer;
		myTimer = t;
	//	this.app = app;
		
		consistentState = "";
	}
	
	public void run() {
		
		
		diff_match_patch dmp = new diff_match_patch();
	//	String currText = app.recvTextArea.getText();
	/*	
		if (currText.equals(consistentState) == false) {
			LinkedList<diff_match_patch.Diff> diff = dmp.diff_main (consistentState, currText);
			dmp.diff_cleanupSemantic(diff);
			LinkedList<diff_match_patch.Patch> patchList = dmp.patch_make(consistentState, currText, diff);
			
			TimeStampedMessage m = new TimeStampedMessage(app.destField.getText(), myPasser.getMyName(), "abc",
					"abc", patchList, false, true);
			m.setMsgType("SendDocumentChanges");
			myPasser.send(m);
			noChange = false;
		
		}
		else {
			if (noChange != true) {
				TimeStampedMessage m = new TimeStampedMessage(app.destField.getText(), myPasser.getMyName(), "abc",
						"abc", currText, false, true);
				m.setMsgType("MulticastDocumentState");
				myPasser.send(m);
			}
			noChange = true;
		}
		
		Message data = (myPasser.receive());
		
		
		if (data != null) {
			
			if (data.getMsgType().equals("MulticastDocumentState")) {
				if (noChange) {
					// check the priority
					int position = app.recvTextArea.getCaretPosition();
					app.recvTextArea.setText((String)data.getPayload());
					try {
						if (position < app.recvTextArea.getText().length()) {
							app.recvTextArea.setCaretPosition(position);
						}	
					}catch (Exception e) {
						System.out.println ("DBUG : got error in setting position\n");
						
					}
				}
				consistentState = (String)data.getPayload();
				return;
			}
			
			if (myPasser.getMyName().contains(data.getPhySender())) {
				return;
			}
			LinkedList<diff_match_patch.Patch> patches = (LinkedList<diff_match_patch.Patch>) (data.getPayload());
			if (patches == null) {
				return;
			}
			Object[] result = dmp.patch_apply(patches, currText);
			consistentState = (String)result[0];
			int position = app.recvTextArea.getCaretPosition();
			app.recvTextArea.setText((String)result[0]);
			if (position > app.recvTextArea.getCaretPosition()) {
				app.recvTextArea.setCaretPosition(position);
			}
			
		}
		else {
			consistentState = currText; 
		}
		*/
	}
}

